package cn.itsource.ldj.org.controller;

import cn.itsource.ldj.org.domain.EmpLoyee;
import cn.itsource.ldj.org.query.EmployeeQuery;
import cn.itsource.ldj.org.service.IEmpLoyeeService;
import cn.itsource.ldj.util.AjaxResult;
import cn.itsource.ldj.util.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@CrossOrigin 解决跨域问题，添加cors头，不建议用，
@RestController // 复合注解，相当于@Controller和ResponseBody这两个注解
@RequestMapping("/emp") // 请求后台地址
public class EmpLoyeeController {

    @Autowired
    private IEmpLoyeeService empLoyeeService;


    /* 查询所有对象 */
    @GetMapping // 必须以get请求进入这个查询全部方法
    public List<EmpLoyee> findAll() {
        try {
            return empLoyeeService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /* 查询单个对象 */
    @GetMapping("/{id}")
    public EmpLoyee findOne(@PathVariable("id") Long id) {
        try {
            return empLoyeeService.findOne(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /* 添加和修改 */
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody EmpLoyee empLoyee) {
        try {
            /* 如果传入的对象有id，执行修改方法，否则执行添加方法 */
            if (empLoyee.getId() != null){
                empLoyeeService.update(empLoyee);
            } else {
                empLoyeeService.save(empLoyee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    /* 删除方法 */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            empLoyeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    /* 分页查询和高级查询 */
    @PostMapping
    public QueryResult<EmpLoyee> queryPage(@RequestBody EmployeeQuery employeeQuery) {
        try {
            return empLoyeeService.queryPage(employeeQuery);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /* 批量删除 */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids) {
        System.out.println(ids);
        try {
            empLoyeeService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

}
